package com.htu.study.service.serviceImpl.user;

import com.htu.study.pojo.User;
import com.htu.study.service.serviceImpl.user.utils.JwtUtil;
import com.htu.study.service.serviceImpl.user.utils.UserDetailsImpl;
import com.htu.study.service.user.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    AuthenticationManager authenticationManager;
    @Override
    public Map<String, String> getToken(String user_name, String user_password) {
        // 封装用户名、密码，密码会封装成加密后的
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user_name, user_password);

        // 登录(登录失败会自动处理)
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 取出用户
        UserDetailsImpl loginUser = (UserDetailsImpl) authenticate.getPrincipal();
        User user = loginUser.getUser();
        String jwt = JwtUtil.createJWT(user.getUserId().toString());

        Map<String, String> map = new HashMap<>();
        map.put("error_message", "success");
        map.put("token", jwt);//"token 要和前端对应"
        return map;
    }
}
